import React, { useEffect, useRef, useState } from 'react';
import { Animated, View, Button, StyleSheet, Text, ScrollView, TextInput, LayoutChangeEvent} from 'react-native';
import { Tester, TestCase, TestSuite } from '@rnoh/testerino';
import {
  TabView,
  TabBar,
  SceneMap,
  NavigationState,
  SceneRendererProps,
  TabDescriptor,
  Layout,
  TabBarIndicator
} from "react-native-tab-view";

export function NewTabViewExample() {
  // 选项卡视图的状态,
  type State = NavigationState<{
    key: string,
    title: string,
  }>;

  // 第一个选项卡的页面
  const FirstRoute = () => (
    <View style={{ flex: 1, backgroundColor: '#ff4081' }}>
      <Text
        style={{
          width: "100%",
          height: "100%",
          fontWeight: "bold",
        }}
      >
        {swipeStr}
      </Text>
    </View>
  );

  // 第二个选项卡的页面
  const SecondRoute = () => (
    <View style={{ flex: 1, backgroundColor: '#673ab7' }}>
      <Text
        style={{
          width: "100%",
          height: "100%",
          fontWeight: "bold",
        }}
      >
        {swipeStr}
      </Text>
    </View>
  );

  // 第三个选项卡的页面
  const ThirdRoute = () => (
    <View style={{ flex: 1, backgroundColor: '#38e0f2' }}>
      <Text
        style={{
          width: "100%",
          height: "100%",
          fontWeight: "bold",
        }}
      >
        {swipeStr}
      </Text>
    </View>
  );

  // 第四个选项卡的页面
  const FourthRoute = () => (
    <View style={{ flex: 1, backgroundColor: '#38e0f2' }}>
      <Text
        style={{
          width: "100%",
          height: "100%",
          fontWeight: "bold",
        }}
      >
        {swipeStr}
      </Text>
    </View>
  );

  const renderLazyPlaceholder = () => (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text>Loading...</Text>
    </View>
  );
  const renderLazyPlaceholderNone = () => (
    <View style={{ flex: 1, backgroundColor: '#38e0f2' }}>
      <Text
        style={{
          width: "100%",
          height: "100%",
          fontWeight: "bold",
        }}
      >
      </Text>
    </View>
  );

  // 用于 renderScene 道具的函数, 接受route.key 映射到 React 组件的对象
  const renderScene = SceneMap({
    first: FirstRoute,
    second: SecondRoute,
    third: ThirdRoute,
    fourth: FourthRoute
  });

const renderTabBarItem = (route: any) => {
    const label =
      options[route.key]?.labelText ||
      commonOptions?.labelText ||
      route.title;
    return <Text>{label}</Text>;
  };

  const renderIndicatorFn = (route: any) => {
    styles.indicator.backgroundColor = 'blue'
    return <Text>{route.title}</Text>
  }


  const renderTabBar = (props: any) => (
    <TabBar
      {...props}
      scrollEnabled={scrollEnabled}
      indicatorStyle={styles.indicator}
      style={styles.tabbar} 
      tabStyle={styles.tabStyle}
      renderTabBarItem={tabBarItem ? ({ route }) => renderTabBarItem(route) : undefined}
      renderIndicator={indicator ? (route) => renderIndicatorFn(route) : undefined}
      onTabPress={onTabPress}
      onTabLongPress={onTabLongPress}
      activeColor={activeColor}
      inactiveColor={inactiveColor}
      pressOpacity={pressOpacity}
      indicatorContainerStyle={{ backgroundColor: 'white' }}
      contentContainerStyle={{ 
        backgroundColor: 'white' ,
        flexDirection: tabBarDirection === 'rtl' ? 'row-reverse' : 'row', 
      }}
      gap={gap}

      layout={tabBarLayout}
      direction={tabBarDirection}
      options={tabBarOptions}
    >
    </TabBar>
  );

  const [routes] = React.useState([
    { key: "first", title: "First" },
    { key: "second", title: "Second" },
    { key: "third", title: "Third" },
    { key: "fourth", title: "Fourth" },
  ]);

  const onSwipeStart = () => {
    setSwipeStr('滑动开始')
  };

  const onSwipeEnd = () => {
    setSwipeStr('滑动结束')
  };

  const onTabPress = () => {
    setSwipeStr('按钮按下')
  }

  const onTabLongPress = () => {
    setSwipeStr('按钮长按')
  }

  // 初始布局
  const initialLayout = { width: 200, height: 500 }

  const [index, setIndex] = React.useState(0);
  const [showRenderTabBar, setShowRenderTabBar] = React.useState(true);
  const [showTabBar, setShowTabBar] = React.useState('top');
  const [showLazy, setshowLazy] = React.useState(true);
  const [preload, setPreload] = React.useState(0);
  const [boardDismiss, setBoardDismiss] = React.useState('auto');
  const [showSwipeEnabled, setShowSwipeEnabled] = React.useState(true);
  const [animation, setAnimation] = React.useState(true);
  const [swipeStr, setSwipeStr] = React.useState('');
  const [initial, setInitial] = React.useState(true);
  const [overScroll, setOverScroll] = React.useState<'auto' | 'always' | 'never'>('auto');
  const [activeColor, setActiveColor] = React.useState('blue');
  const [inactiveColor, setInactiveColor] = React.useState('gray');
  const [pressOpacity, setPressOpacity] = React.useState(0.5);
  const [scrollEnabled, setScrollEnabled] = React.useState(true);
  const [gap, setGap] = React.useState(0);
  const [tabBarItem, setTabBarItem] = React.useState(false);
  const [indicator, setIndicator] = React.useState(false);
  const [direction, setDirection] = React.useState('ltr');
  const [options, setOptions] = useState<Record<string, TabDescriptor<{ key: string; title: string }>>>({});
  const [commonOptions, setCommonOptions] = useState<TabDescriptor<{ key: string; title: string }>>({});
  const [tabBarDirection, setTabBarDirection] = useState('ltr');
  const [tabBarOptions, setTabBarOptions] = useState<Record<string, TabDescriptor<{ key: string; title: string }>>>({});
  const [tabBarLayout, setTabBarLayout] = useState<Layout>({ width: 0, height: 0 });
  
  const tabBarContainerRef = useRef<View>(null);
  const onTabBarLayout = (event: LayoutChangeEvent) => {
    const { width, height } = event.nativeEvent.layout;
    setTabBarLayout({ width, height });
  };

  return (
    <View style={{ flex: 1 }}>
      <Tester>
        <TestSuite name={'TabViewTest'}>
          <TestCase itShould={'TabView show'}>
            <View 
              ref={tabBarContainerRef}
              onLayout={onTabBarLayout}
              style={{
                padding: 0,
                margin: 0,
                width: 350,
                height: 200,
            }}>
              <TabView
                style={{
                  flex: 1,
                  width: 350,
                  height: 100,
                  backgroundColor: "#6D8585",
                }}
                navigationState={{ index, routes }}
                renderScene={renderScene}
                onIndexChange={setIndex}
                renderTabBar={showRenderTabBar ? renderTabBar : undefined}
                tabBarPosition={showTabBar === 'top' ? 'top' : 'bottom'}
                lazy={showLazy}
                lazyPreloadDistance={preload}
                renderLazyPlaceholder={showLazy == true ? renderLazyPlaceholder : renderLazyPlaceholderNone}
                keyboardDismissMode={boardDismiss == 'auto' ? 'auto' : (boardDismiss == 'none' ? 'none' : 'on-drag')}
                swipeEnabled={showSwipeEnabled}
                animationEnabled={animation}
                onSwipeStart={onSwipeStart}
                onSwipeEnd={onSwipeEnd}
                initialLayout={initial ? initialLayout : undefined}
                overScrollMode={overScroll}
                direction={direction}
                commonOptions={commonOptions}
                options={options}
              />
            </View>
          </TestCase>
        </TestSuite>
      </Tester>

      <ScrollView bounces={false}>
        <Tester style={{ paddingBottom: 80 }}>
          <TestSuite name={'TabViewTest'}>
            <TestCase itShould={'TabView renderTabBar'}>
              <View style={styles.flex_row} >
                <Text style={{ flex: 0.25 }}>renderTabBar:{showRenderTabBar}</Text>
                <Text style={{ backgroundColor: "orange", flex: 0.25 }} onPress={() => { setShowRenderTabBar(true); }} >设置renderTabBar</Text>
                <Text style={{ backgroundColor: "orange", flex: 0.25, marginLeft: 10 }} onPress={() => { setShowRenderTabBar(false); }} >关闭renderTabBar</Text>
              </View>
            </TestCase>

            <TestCase itShould={'TabView gap'}>
              <View style={styles.flex_row} >
                <Text style={{ flex: 0.25 }}>gap:{gap}</Text>
                <Text style={{ backgroundColor: "orange", flex: 0.25 }} onPress={() => { setGap(0); }} >0</Text>
                <Text style={{ backgroundColor: "orange", flex: 0.25, marginLeft: 10 }} onPress={() => { setGap(10); }} >10</Text>
                <Text style={{ backgroundColor: "orange", flex: 0.25, marginLeft: 10 }} onPress={() => { setGap(20); }} >20</Text>
              </View>
            </TestCase>

            <TestCase itShould={'TabView direction'}>
              <View style={styles.flex_row} >
                <Text style={{ flex: 0.25 }}>TabView direction:{direction}</Text>
                <Text style={{ backgroundColor: "orange", flex: 0.25 }} onPress={() => { setDirection('rtl'); }} >rtl</Text>
                <Text style={{ backgroundColor: "orange", flex: 0.25, marginLeft: 10 }} onPress={() => { setDirection('ltr'); }} >ltr</Text>
              </View>
            </TestCase>

            <TestCase itShould={'TabBar direction'}>
              <View style={styles.flex_row}>
                <Text style={{ flex: 0.25 }}>TabBar direction: {tabBarDirection}</Text>
                <Text style={{ backgroundColor: 'orange', flex: 0.25 }} onPress={() => { setTabBarDirection('rtl'); }}>rtl</Text>
                <Text style={{ backgroundColor: 'orange', flex: 0.25, marginLeft: 10 }} onPress={() => { setTabBarDirection('ltr'); }}>ltr</Text>
              </View>
            </TestCase>

            <TestCase itShould={'TabBar options'}>
              <View style={styles.flex_row}>
                <Text style={{ flex: 0.25 }}>TabBar options: {JSON.stringify(tabBarOptions)}</Text>
                <Text style={{ backgroundColor: 'orange', flex: 0.25 }} onPress={() => {
                  setTabBarOptions({
                    first: { labelText: 'TabBar First Label' },
                    second: { labelText: 'TabBar Second Label' },
                  });
                }}>设置 options</Text>
                <Text style={{ backgroundColor: 'orange', flex: 0.25, marginLeft: 10 }} onPress={() => { setTabBarOptions({}); }}>清空 options</Text>
              </View>
            </TestCase>

            <TestCase itShould={'TabView options'}>
              <View style={styles.flex_row}>
                <Text style={{ flex: 0.25 }}>TabView options: {JSON.stringify(options)}</Text>
                <Text style={{ backgroundColor: 'orange', flex: 0.25 }} onPress={() => {
                  setOptions({
                    first: {
                      sceneStyle: { padding: 5 },
                    },
                    second: {
                      sceneStyle: { padding: 20 },
                    },
                    third: {
                      sceneStyle: { padding: 40 },
                    }
                  });
                }}>设置 options</Text>
                <Text style={{ backgroundColor: 'orange', flex: 0.25, marginLeft: 10 }} onPress={() => { setOptions({}); }}>清空 options</Text>
              </View>
            </TestCase>
            
            <TestCase itShould={'TabView commonOptions'}>
              <View style={styles.flex_row}>
                <Text style={{ flex: 0.25 }}>TabView commonOptions: {JSON.stringify(commonOptions)}</Text>
                <Text style={{ backgroundColor: 'orange', flex: 0.25 }} onPress={() => {
                  setCommonOptions({
                    sceneStyle: { padding: 40 }
                  });
                }}>设置commonOptions</Text>
                <Text style={{ backgroundColor: 'orange', flex: 0.25, marginLeft: 10 }} onPress={() => { setCommonOptions({}); }}>清空 commonOptions</Text>
              </View>
            </TestCase>

            <TestCase itShould={'TabBar layout'}>
              <View style={styles.flex_row}>
                <Text style={{ flex: 0.5 }}>TabBar layout: {JSON.stringify(tabBarLayout)}</Text>
              </View>
            </TestCase>
          </TestSuite>
        </Tester>
      </ScrollView>
    </View>
  );
}


const styles = StyleSheet.create({
  tabbar: {
    backgroundColor: "#1af0b7",
    height: 70,
    width: 350,
  },
  indicator: {
    backgroundColor: "#ffeb3b",
    width: 175,
    height: 5,
  },
  tabStyle: {
    height: 65,
    width: 175,
    backgroundColor: "pink",
  },
  sceneContainer: {
    width: 150,
    height: 150,
    color: 'blue',
    backgroundColor: 'blue',
  },
  pager: {
    width: 150,
    height: 150,
    backgroundColor: 'orange',
  },
  input: {
    height: 40,
    borderColor: 'gray',
    borderWidth: 1,
    padding: 10,
  },
  flex_row: {
    flexDirection: "row",
    alignItems: 'center',
    height: 50,
    padding: 0,
    marginTop: 2,
  },
  scenc: {
    backgroundColor: 'yellow',
  }
});


export default NewTabViewExample